<?php
/**
 * 楼宇控制器
 * User: John
 * Date: 16-12-29
 * Time: 下午4:56
 */
namespace app\backend\controller;

use app\backend\controller\traits\AuthManager;
use app\backend\model\Bank;
use app\backend\model\BatchPayment;
use app\backend\model\Building;
use app\backend\model\Lease;
use app\backend\model\Member;
use app\backend\model\Photo;
use app\backend\model\Trust;
use app\index\controller\IndexController;
use Business\TongLianBatchPayment\BatchTranx;
use think\Controller;

class BuildingController extends Controller
{
    use AuthManager;
    private $_memberId = null;
    private $_dtype    = null;
    private $_pdtype   = null;
    private $_pmid     = null;
    private $_allAuth  = [];
    public function __construct()
    {
        parent::__construct();
        $memberInfo = $this->getLoginInfo();
        $this->_memberId = $memberInfo['mid'];
        $this->_dtype    = $memberInfo['dtype'];
        $this->_pdtype   = $memberInfo['p_dtype'];
        $this->_pmid     = $memberInfo['p_mid'];
        $this->_allAuth  = $this->getPower($this->_memberId, $this->_dtype);
    }

    /**
     * 获取楼宇模型
     * @date   2017-3-14
     * @author wuhao
     *
     * @return Building
     */
    public function getBuildingModel()
    {
        static $model;
        if (!$model) {
            $model = new Building();
        }
        return $model;
    }

    /**
     * 新增楼宇
     */
    public function setBuilding()
    {
        if (!in_array($this->getOper('setBuilding'), $this->_allAuth)) {
            $this->apiReturn(400,[],'无权操作');
        }

        $province       = I('post.province', '', 'intval');           //省
        $city           = I('post.city', '', 'intval');               //市
        $country        = I('post.country', '', 'strval');            //区
        $name           = I('post.name', '', 'strval');               //楼宇名称
        $type           = I('post.type', '', 'intval');               //楼宇类型
        $address        = I('post.address', '', 'strval');            //详细地址
        $propertyId     = I('post.property_id', 0, 'intval');         //物业公司
        $hydropowerId   = I('post.hydropower_id', 0, 'intval');       //水电公司
        $buildingNumber = I('post.building_number', '', 'strval');    //楼宇栋数
        $buildingCount  = I('post.building_count', '', 'intval');     //楼栋数量
        $tradeArea      = I('post.trade_area', 0, 'intval');          //商圈属性
        $feeRatio       = I('post.fee_ratio', 0, 'floatval');         //公摊比例
        $floorNum       = I('post.building_floor', 0, 'intval');      //层数
        $liftNum        = I('post.lift_num', 0, 'intval');            //电梯数
        $parkingNum     = I('post.parking_num', 0, 'intval');         //车位数
        $photo          = I('post.photo', '', 'strval');              //楼宇图片地址，按','分割

        if (!$province ||!$city ||!$name ||!$type ||!$address ||!$propertyId || !$hydropowerId || !$buildingNumber
            || !$buildingCount || (!$tradeArea && $tradeArea!==0)) {
            $this->apiReturn(400, [], '有信息未填');
        }
        if (!$country) {
            //区县为空判断一下这个地区有没有区县
            $indexModel = new IndexController();
            $ctInfo = $indexModel->getCountrys($city);
            if ($ctInfo) {
                $this->apiReturn(400, [], '有信息未填');
            }
        }

        if ($res = $this->getBuildingModel()->checkBuilding($name, $buildingNumber, $province, $city, $country)) {
            $this->apiReturn(202, [], '该区域楼宇已经存在');
        }

        $data = [
            'mid'             => $this->_pmid,
            'province'        => $province,
            'city'            => $city,
            'country'         => $country,
            'name'            => $name,
            'type'            => $type,
            'address'         => $address,
            'property_id'     => $propertyId,
            'hydropower_id'   => $hydropowerId,
            'building_number' => $buildingNumber,
            'building_count'  => $buildingCount,
            'trade_area'      => $tradeArea,
            'fee_ratio'       => $feeRatio,
            'building_floor'  => $floorNum,
            'lift_num'        => $liftNum,
            'parking_num'     => $parkingNum,
        ];

        $data['time'] = time();
        $buildingId = $this->getBuildingModel()->addBuilding($data);
        if ($buildingId) {
            if ($photo) {
                //有传图片的话
                $photoArr = explode(',', trim($photo));
                $photoModel = new Photo();
                $photoInfo = [];
                foreach ($photoArr as $k => $v) {
                    $photoInfo[] = [
                        'rid'         => $buildingId,
                        'rtype'       => 1,
                        'srtype'      => 1,
                        'url'         => trim($v),
                        'create_user' => $this->_pmid,
                        'create_time' => time(),
                    ];
                }
                $resPhoto = $photoModel->addAll($photoInfo);
                if (!$resPhoto) {
                    zft_log('photo/add_building', $photoModel->getLastSql());
                }
            }
            $this->apiReturn(200, [], '创建成功');
        } else {
            zft_log('build/add_build_fail', $this->getBuildingModel()->getLastSql());
            $this->apiReturn(201, [], '创建失败');
        }
    }

    /**
     * 获取某栋楼的信息
     */
    public function getBuildingDetail()
    {
        $buildingId = I('post.building_id', '', 'intval');
        //$buildingId = 72;
        if (!is_numeric($buildingId) || $buildingId<=0) {
            $this->apiReturn(400, [], '参数错误');
        }
        $res = $this->getBuildingModel()->getBuildingDetail($buildingId);
        if (!$res) {
            $this->apiReturn(201, [], '获取不到楼宇信息');
        }
        //获取图片
        $photoModel = new Photo();
        $photoArr   = $photoModel->getPhoto(['rid' => $buildingId, 'rtype' => 1], 'url');
        if ($photoArr) {
            $res['photo'] = $photoArr;
        } else {
            $res['photo'] = [];
        }

        $this->apiReturn(200, $res, '');
    }

    /**
     * 编辑楼宇
     */
    public function editBuilding()
    {
        if (!in_array($this->getOper('editBuilding'), $this->_allAuth)) {
            $this->apiReturn(400,[],'无权操作');
        }

        $buildId          = I('post.build_id', '', 'intval');           //楼宇id
        $province         = I('post.province', '', 'intval');           //省
        $city             = I('post.city', '', 'intval');               //市
        $country          = I('post.country', '', 'strval');            //区
        $name             = I('post.name', '', 'strval');               //楼宇名称
        $type             = I('post.type', '', 'intval');               //楼宇类型
        $address          = I('post.address', '', 'strval');            //详细地址
        $propertyId       = I('post.property_id', '', 'intval');        //物业公司
        $hydropowerId     = I('post.hydropower_id', '', 'intval');      //水电公司
        $buildingNumber   = I('post.building_number', '', 'strval');    //楼宇栋数
        $buildingCount    = I('post.building_count', '', 'intval');     //楼栋数量
        $tradeArea        = I('post.trade_area', 0, 'intval');          //商圈属性
        $buildingFloor    = I('post.building_floor', 0, 'intval');      //楼层
        $feeRatio         = I('post.fee_ratio', 0, 'intval');          //公摊比
        $liftNum          = I('post.lift_num', 0, 'intval');          //电梯数
        $parkingNum       = I('post.parking_num', 0, 'intval');          //车位数
        $oldPhoto         = I('post.old_photo', '', 'strval');          //楼宇原先的图片
        $photo            = I('post.photo', '', 'strval');              //楼宇图片

        if (!$buildId || !$province || !$city  ||!$name ||!$type ||!$address ||!$propertyId || !$hydropowerId || !$buildingNumber
            || !$buildingCount || (!$tradeArea && $tradeArea!==0)) {
            $this->apiReturn(400, [], '有信息未填');
        }
        if (!$country) {
            $indexModel = new IndexController();
            $ctInfo = $indexModel->getCountrys($city);
            if ($ctInfo) {
                $this->apiReturn(400, [], '有信息未填');
            }
        }

        //判断楼宇是否存在
        $buildingInfo = $this->getBuildingModel()->getBuildingInfo($buildId,
            'id,mid,province,city,country,name,type,address,property_id,hydropower_id,building_number,building_count,trade_area,building_floor,fee_ratio,lift_num,parking_num,is_delete');
        if (!$buildingInfo) {
            $this->apiReturn(401, [], '楼宇不存在!');
        }
        if ($this->_pmid != $buildingInfo['mid']) {
            $this->apiReturn(401, [], '非创建人,不能操作!');
        }

        //判断这个楼宇下的房屋是否存在已出租的或已托管的
        $houseArray = $this->getBuildingModel()->getHouseStatusByBuildId($buildId);
        if (!empty($houseArray)) {
            $this->apiReturn(402, [], '该楼宇存在已出租或已托管的房源,不能修改');
        }

        //判断修改的信息是否有重复的情况发生
        $modifyId = $this->getBuildingModel()->checkBuilding($name, $buildingNumber, $province, $city, $country);
        if ($modifyId && $modifyId['id'] != $buildId) {
            $this->apiReturn(202, [], '该区域楼宇名称已经存在');
        }

        //判断信息是否有改动
        $modify = 1;
        if (($buildingInfo['id'] == $buildId) && ($buildingInfo['province'] == $province) && ($buildingInfo['city'] == $city) && ($buildingInfo['country'] == $country) &&
            ($buildingInfo['name'] == $name) &&($buildingInfo['type'] == $type) &&($buildingInfo['address'] == $address) &&($buildingInfo['property_id'] == $propertyId) &&
            ($buildingInfo['building_number'] == $buildingNumber) && ($buildingInfo['building_count'] == $buildingCount) && ($buildingInfo['trade_area'] == $tradeArea)
             && $buildingInfo['building_floor'] == $buildingFloor && $buildingInfo['fee_ratio'] == $feeRatio && $buildingInfo['lift_num'] == $liftNum && $buildingInfo['parking_num'] == $parkingNum) {
            //楼宇基本信息未修改
            $modify = 0;

            if ($photo == $oldPhoto) {
                $this->apiReturn(202, [], '信息未作修改');
            }

        }

        //更新信息
        $data = [
            'province'        => $province,
            'city'            => $city,
            'country'         => $country,
            'name'            => $name,
            'type'            => $type,
            'address'         => $address,
            'property_id'     => $propertyId,
            'hydropower_id'   => $hydropowerId,
            'building_number' => $buildingNumber,
            'building_count'  => $buildingCount,
            'trade_area'      => $tradeArea,
            'building_floor'  => $buildingFloor,
            'fee_ratio'       => $feeRatio,
            'lift_num'        => $liftNum,
            'parking_num'     => $parkingNum,
        ];

        if ($modify == 1) {
            $res = $this->getBuildingModel()->updateBuilding($data, ['id' => $buildId]);
        }

        if ($photo != $oldPhoto) {
            //有传图片的话
            $photoModel = new Photo();
            //先删除原有图片
            $photoModel->deletePhoto($buildId, 1);
            //再保存最新的
            $photoArr  = explode(',', trim($photo));
            $photoInfo = [];
            foreach ($photoArr as $k => $v) {
                $photoInfo[] = [
                    'rid'         => $buildId,
                    'rtype'       => 1,
                    'srtype'      => 1,
                    'url'         => trim($v),
                    'create_user' => $this->_pmid,
                    'create_time' => time(),
                ];
            }
            $resPhoto = $photoModel->addAll($photoInfo);
            if (!$resPhoto) {
                zft_log('photo/edit_building', $photoModel->getLastSql());
            }
        }
        if (($modify == 1 && $res) || $modify == 0) {
            $this->apiReturn(200, [], '编辑成功');
        } else {
            zft_log('build/update_build_fail', $this->getBuildingModel()->getLastSql());
            $this->apiReturn(201, [], '编辑失败');
        }
    }

    /**
     * 删除楼宇
     * @date   2017-3-7
     * @author wuhao
     *
     * @param int   $buildId  楼宇id
     * @return json
     */
    public function deleteBuilding()
    {
        if (!in_array($this->getOper('deleteBuilding'), $this->_allAuth)) {
            $this->apiReturn(400,[],'无权操作');
        }
        $buildId  = I('post.build_id', '', 'intval');           //要删除的楼宇id
        if (!is_numeric($buildId) || $buildId == 0) {
            $this->apiReturn(400, [], '参数错误');
        }
        //判断楼宇是否存在
        $buildingInfo = $this->getBuildingModel()->getBuildingInfo($buildId, 'id, mid');
        if (!$buildingInfo) {
            $this->apiReturn(401, [], '楼宇不存在!');
        }
        if ($this->_pmid != $buildingInfo['mid']) {
            $this->apiReturn(401, [], '非创建人,不能操作!');
        }

        //判断这个楼宇下的房屋是否存在已出租的或已托管的
        $houseArray = $this->getBuildingModel()->getHouseStatusByBuildId($buildId);
        if (!empty($houseArray)) {
            $this->apiReturn(402, [], '该楼宇存在已出租或已托管的房源,不能删除');
        }
        //删除楼宇
        $res = $this->getBuildingModel()->deleteBuilding($buildId);
        if ($res) {
            //判断楼宇是否有房源
            $checkHouse = $this->getBuildingModel()->checkHouseByBuildingId($buildId);
            if ($checkHouse) {
                //同时删除房源
                $deleteInfo = $this->getBuildingModel()->deleteHouseByBuildingId($buildId);
                if (!$deleteInfo) {
                    zft_log('build/delete_house_fail', $this->getBuildingModel()->getLastSql());
                }
            }
            $this->apiReturn(200, [], '删除成功');
        } else {
            zft_log('build/delete_build_fail', $this->getBuildingModel()->getLastSql());
            $this->apiReturn(400, [], '删除失败');
        }
    }

    /**
     * 楼宇失效处理
     * @date   2017-4-1
     * @author wuhao
     *
     * @param int $build_id 楼宇id
     * @param int $status   状态  1=失效 0=恢复正常(暂时不要)
     * @return json
     */
    public function setForbidBuilding()
    {
        if (!in_array($this->getOper('forbidBuilding'), $this->_allAuth)) {
            $this->apiReturn(400,[],'无权操作');
        }
        $buildId  = I('post.build_id', 0, 'intval');           //要删除的楼宇id
        $status   = I('post.status', 0, 'intval');    //失效状态 1=失效
        if (!is_numeric($buildId) || $buildId == 0 || !in_array($status, [1])) {
            $this->apiReturn(400, [], '参数错误');
        }
        //判断楼宇原来的状态
        $buildingInfo = $this->getBuildingModel()->getBuildingInfo($buildId, 'id, mid, is_delete');
        if (!$buildingInfo) {
            $this->apiReturn(401, [], '楼宇不存在!');
        }
        if ($this->_pmid != $buildingInfo['mid']) {
            $this->apiReturn(401, [], '非创建人,不能操作!');
        }
        if ($buildingInfo['is_delete'] == $status) {
            $this->apiReturn(401, [], '不需要再次更新状态!');
        }

        //失效操作
        $res = $this->getBuildingModel()->updateBuilding(['is_delete' => $status], ['id' => $buildId]);
        if (!$res) {
            zft_log('build/update_build_fail', $this->getBuildingModel()->getLastSql());
            $this->apiReturn(400, [], '失效处理失败');
        } else {
            //判断楼宇是否有房源
            $checkHouse = $this->getBuildingModel()->checkHouseByBuildingId($buildId);
            if ($checkHouse) {
                //同时更新房源为删除状态
                $updateInfo = $this->getBuildingModel()->forbidHouseByBuildingId($buildId);
                if (!$updateInfo) {
                    zft_log('build/update_house_fail', $this->getBuildingModel()->getLastSql());
                }
            }
            $this->apiReturn(200, [], '失效处理成功');
        }
    }

    /**
     * 新增房源
     */
    public function setHouse()
    {
        if (!in_array($this->getOper('setHouse'), $this->_allAuth)) {
            $this->apiReturn(400,[],'无权操作');
        }

        $buildId     = I('post.building_id', '', 'intval');     //楼宇ID
        $number      = I('post.number', '', 'intval');          //楼栋
        $floor       = I('post.floor', '', 'intval');           //楼层
        $room        = I('post.room', '', 'strval');            //房号
        $price       = I('post.price', 0);                     //房租
        $priceType   = I('post.price_type', 0, 'intval');      //房租方式  0=按月 1=按平方米
        $priceWater  = I('post.price_water', 0);               //水费
        $pricePower  = I('post.price_power', 0);               //电费
        $property    = I('post.property', 0);                  //物业费
        $feeWater    = I('post.fee_water', 0);                 //公摊水
        $feePower    = I('post.fee_power', 0);                 //公摊电
        $others      = I('post.others', 0);                    //其他费用
        $mid         = I('post.owner_id', '', 'intval');        //房源归属
        $area        = I('post.area', 0);                       //面积
        $houseType   = I('post.type_photo', '', 'strval');      //户型图
        $otherPhoto  = I('post.other_photo', '', 'strval');     //其他图片

        //$buildId = 12;
        if (!is_numeric($buildId) || $buildId<=0 || !is_numeric($number) || $number<0 || !is_numeric($floor) || $floor<0
            || !$room || !is_numeric($price) || $price<0 || !in_array($priceType, [0, 1]) || !is_numeric($priceWater) || $priceWater<0
            || !is_numeric($pricePower) || $pricePower<0 || !is_numeric($property) || $property<0 || !is_numeric($feeWater)
            || $feeWater<0 || !is_numeric($feePower) || $feePower<0 || !is_numeric($mid) || $mid<=0|| !is_numeric($area) || $area<=0) {
            $this->apiReturn(202, [], '缺少参数或参数有误');
        }

        $houseNumber = $buildId.time().genRandomNum(4);
        $data = [
            'building_id'   => $buildId,
            'number'        => $number,
            'floor'         => $floor,
            'room'          => $room,
            'price_type'    => $priceType,
            'price'         => (is_numeric($price) && $price>0) ? fen($price) :0,
            'price_water'   => (is_numeric($priceWater) && $priceWater>0) ? fen($priceWater) :0,
            'price_power'   => (is_numeric($pricePower) && $pricePower>0) ?fen($pricePower) :0,
            'property'      => (is_numeric($property) && $property>0) ? fen($property) :0,
            'fee_water'     => (is_numeric($feeWater) && $feeWater>0) ? fen($feeWater) :0,
            'fee_power'     => (is_numeric($feePower) && $feePower>0) ? fen($feePower) :0,
            'others'        => (is_numeric($others) && $others>0)  ? fen($others) : 0,
            'mid'           => $mid,
            'house_number'  => $houseNumber,
            'area'          => $area,
        ];

        if ($this->getBuildingModel()->checkHouseOwner($buildId, $number, $floor, $room)) {
            $this->apiReturn(202, [], '该楼宇的房源已经存在');
        }

        $data['time'] = time();
        $id = $this->getBuildingModel()->addHouse($data);
        if ($id) {
            $photoModel = new Photo();
            if ($houseType) {
                //户型图有传
                $houseTypeArr = explode(',', trim($houseType));
                $photoInfo = [];
                foreach ($houseTypeArr as $h => $val) {
                    $photoInfo[] = [
                        'rid'         => $id,
                        'rtype'       => 2,
                        'srtype'      => 1,
                        'url'         => $val,
                        'create_user' => $this->_pmid,
                        'create_time' => time(),
                    ];
                }
                $resPhoto = $photoModel->addAll($photoInfo);
                if (!$resPhoto) {
                    zft_log('photo/add_house', $photoModel->getLastSql());
                }
            }

            if ($otherPhoto) {
                //有传其他图片
                $otherArr = explode(',', trim($otherPhoto));
                $otherInfo = [];
                foreach ($otherArr as $k => $v) {
                    $otherInfo[] = [
                        'rid'         => $id,
                        'rtype'       => 2,
                        'srtype'      => 2,
                        'url'         => $v,
                        'create_user' => $this->_pmid,
                        'create_time' => time(),
                    ];
                }
                $resPhoto = $photoModel->addAll($otherInfo);
                if (!$resPhoto) {
                    zft_log('photo/add_house', $photoModel->getLastSql());
                }
            }
            $this->apiReturn(200, [], '创建成功');
        } else {
            zft_log('build/add_house_fail', $this->getBuildingModel()->getLastSql());
            $this->apiReturn(201, [], '创建失败##'.$this->getBuildingModel()->getError());
        }
    }

    /**
     * 获取房源信息用于编辑
     * @date   2017-3-8
     * @author wuhao
     *
     * @return json
     */
    public function getHouseDetail()
    {
        $houseId = I('post.id', '', 'intval');
        //$houseId = 61;
        if (!is_numeric($houseId) || $houseId<=0) {
            $this->apiReturn(402, [], '参数错误');
        }

        $res = $this->getBuildingModel()->getHouseDetail($houseId);
        if (!$res) {
            $this->apiReturn(202, [], '没有相应的房源信息');
        }
        $res['price']       = yuan($res['price']);
        $res['property']    = yuan($res['property']);
        $res['fee_water']   = yuan($res['fee_water']);
        $res['fee_power']   = yuan($res['fee_power']);
        $res['price_water'] = yuan($res['price_water']);
        $res['price_power'] = yuan($res['price_power']);
        if (!empty($res['others'])) {
            $res['others'] = yuan($res['others']);
        }
        //获取图片
        $photoModel = new Photo();
        $photoArr   = $photoModel->getPhoto(['rid' => $houseId, 'rtype' => 2], 'srtype, url');
        if ($photoArr) {
            $res['photo'] = $photoArr;
        } else {
            $res['photo'] = [];
        }
        $this->apiReturn(200, $res, '');
    }

    /**
     * 编辑房源信息
     * @date   2017-3-8
     * @author wuhao
     *
     * @return json
     */
    public function editHouse()
    {
        if (!in_array($this->getOper('editHouse'), $this->_allAuth)) {
            $this->apiReturn(400,[],'无权操作');
        }

        $buildId       = I('post.building_id', '', 'intval');    //楼宇ID
        $mid           = I('post.owner_id', '', 'intval');       //房源归属
        $number        = I('post.number', '', 'intval');         //楼栋
        $floor         = I('post.floor', '', 'intval');          //楼层
        $room          = I('post.room', '', 'strval');           //房号
        $price         = I('post.price', 0);                     //房租
        $priceType     = I('post.price_type', 0, 'intval');      //房租收取方式 0=按月 1=按每平方米
        $priceWater    = I('post.price_water', 0);               //水费
        $pricePower    = I('post.price_power', 0);               //电费
        $property      = I('post.property', 0);                  //物业费
        $feeWater      = I('post.fee_water', 0);                 //公摊水
        $feePower      = I('post.fee_power', 0);                 //公摊电
        $others        = I('post.others', 0);                    //其他费用
        $houseId       = I('post.id', 0, 'intval');              //房源id
        $area          = I('post.area', 0);                      //面积
        $oldHouseType  = I('post.old_type_photo', '', 'strval');  //旧的户型图片
        $oldOtherPhoto = I('post.old_other_photo', '', 'strval'); //旧的其他图片
        $houseType     = I('post.type_photo', '', 'strval');      //户型图
        $otherPhoto    = I('post.other_photo', '', 'strval');     //其他图片
        //$buildId = 12;

        if (!is_numeric($buildId) || $buildId<=0 || !is_numeric($mid) || $mid <=0 || !is_numeric($number) || $number<0 || !is_numeric($floor) || $floor<0
            || !$room || !is_numeric($price) || $price<0 || !is_numeric($priceWater) || $priceWater<0
            || !is_numeric($property) || $property<0 || !is_numeric($feeWater) || $feeWater<0 || !is_numeric($feePower) || $feePower<0
            || !is_numeric($houseId) || $houseId<=0|| !is_numeric($area) || $area<=0 || !in_array($priceType, [0, 1])) {
            $this->apiReturn(202, [], '缺少参数');
        }

        $houseInfo = $this->getBuildingModel()->getHouseInfo('h.building_id, h.number, h.floor,h.room, h.price_type,h.price, h.price_water,
        h.price_power, h.property,h.fee_water,h.fee_power,h.others,h.area,
        h.id, h.mid, h.status, h.trust_status, b.mid creator', ['h.id' => $houseId]);
        if (!$houseInfo) {
            $this->apiReturn(202, [], '不存在该房源');
        }
        if ($houseInfo[0]['creator'] != $this->_pmid) {
            $this->apiReturn(203, [], '没有权限修改!');
        }
        if ($houseInfo[0]['status'] == 1 || $houseInfo[0]['trust_status'] == 1) {
            $this->apiReturn(204, [], '房源已出租或托管，不能修改');
        }


        $modify = 1;
        if (($houseInfo[0]['building_id'] == $buildId) && ($houseInfo[0]['mid'] == $mid) && ($houseInfo[0]['number'] == $number)
            &&($houseInfo[0]['floor'] == $floor) && ($houseInfo[0]['room'] == $room) && ($houseInfo[0]['price_type'] == $priceType)
            &&($houseInfo[0]['price'] == fen($price)) && ($houseInfo[0]['price_water'] == fen($priceWater)) && ($houseInfo[0]['price_power'] == fen($pricePower))
            &&($houseInfo[0]['property'] == fen($property)) && ($houseInfo[0]['fee_water'] == fen($feeWater)) && ($houseInfo[0]['fee_power'] == fen($feePower))
            &&($houseInfo[0]['others'] == fen($others)) && ($houseInfo[0]['area'] == $area)) {
            //基本信息未改
            $modify = 0;
            if ($oldOtherPhoto == $otherPhoto && $oldHouseType == $houseType) {
                $this->apiReturn(202, [], '信息未作修改');
            }
        }
        $data = [
            'building_id'   => $buildId,
            'mid'           => $mid,
            'number'        => $number,
            'floor'         => $floor,
            'room'          => $room,
            'price_type'    => $priceType,
            'price'         => (is_numeric($price) && $price>0) ? fen($price) : 0,
            'price_water'   => (is_numeric($priceWater) && $priceWater>0) ? fen($priceWater) : 0,
            'price_power'   => (is_numeric($pricePower) && $pricePower>0) ?fen($pricePower) : 0,
            'property'      => (is_numeric($property) && $property>0) ? fen($property) : 0,
            'fee_water'     => (is_numeric($feeWater) && $feeWater>0) ? fen($feeWater) : 0,
            'fee_power'     => (is_numeric($feePower) && $feePower>0) ? fen($feePower) : 0,
            'others'        => (is_numeric($others) && $others>0)  ? fen($others) : 0,
            'id'            => $houseId,
            'area'          => $area,
        ];

        if ($modify == 1) {
            $res = $this->getBuildingModel()->updateHouse($data, ['id' => $houseId]);
        }

        $photoModel = new Photo();
        if ($oldHouseType != $houseType) {
            //户型图有变
            //先删除旧的数据
            $photoModel->deletePhoto($houseInfo[0]['id'], 2, 1);
            $houseTypeArr = explode(',', trim($houseType));
            $photoInfo = [];
            foreach ($houseTypeArr as $k => $v) {
                $photoInfo[] = [
                    'rid'         => $houseInfo[0]['id'],
                    'rtype'       => 2,
                    'srtype'      => 1,
                    'url'         => $v,
                    'create_user' => $this->_pmid,
                    'create_time' => time(),
                ];
            }
            $resPhoto = $photoModel->addAll($photoInfo);
            if (!$resPhoto) {
                zft_log('photo/edit_house', $photoModel->getLastSql());
            }
        }

        if ($oldOtherPhoto != $otherPhoto) {
            //其他房源图有变
            $photoModel->deletePhoto($houseInfo[0]['id'], 2, 2);
            $otherPhotoArr = explode(',', trim($otherPhoto));
            $otherInfo = [];
            foreach ($otherPhotoArr as $a => $b) {
                $otherInfo[] = [
                    'rid'         => $houseInfo[0]['id'],
                    'rtype'       => 2,
                    'srtype'      => 2,
                    'url'         => $b,
                    'create_user' => $this->_pmid,
                    'create_time' => time(),
                ];
            }
            $other = $photoModel->addAll($otherInfo);
            if (!$other) {
                zft_log('photo/edit_house', $photoModel->getLastSql());
            }
        }
        if (($modify == 1 && $res) || $modify == 0) {

            $this->apiReturn(200, [], '编辑成功');
        } else {
            zft_log('build/update_house_fail', $this->getBuildingModel()->getLastSql());
            $this->apiReturn(201, [], '编辑失败##'.$this->getBuildingModel()->getError());
        }
    }

    /**
     * 删除房源信息
     * @date   2017-3-8
     * @author wuhao
     *
     * @param int $id 房源id
     * @return json
     */
    public function deleteHouse()
    {
        if (!in_array($this->getOper('deleteHouse'), $this->_allAuth)) {
            $this->apiReturn(400,[],'无权操作');
        }
        $houseId  = I('post.id', '', 'intval');           //要删除的房源编号
        if (!is_numeric($houseId) || $houseId<=0) {
            $this->apiReturn(400,[],'参数错误');
        }

        //先获取这条房源信息
        $houseInfo = $this->getBuildingModel()->getHouseInfo('h.mid, h.status, h.trust_status', ['h.id' => $houseId]);

        if (!$houseInfo) {
            $this->apiReturn(202, [], '不存在该房源');
        }
        if ($houseInfo[0]['mid'] != $this->_pmid) {
            $this->apiReturn(203, [], '没有权限!');
        }
        if ($houseInfo[0]['status'] == 1 || $houseInfo[0]['trust_status'] == 1) {
            $this->apiReturn(204, [], '房源已出租或托管，不能删除');
        }
        //更新删除状态
        $res = $this->getBuildingModel()->deleteHouse($houseId);
        if ($res) {
            $this->apiReturn(200, [], '删除成功');
        } else {
            zft_log('build/update_house_fail', $this->getBuildingModel()->getLastSql());
            $this->apiReturn(201, [], '删除失败##'.$this->getBuildingModel()->getError());
        }
    }

    /**
     * 房源失效处理
     * @date   2017-3-8
     * @author wuhao
     *
     * @param int $id 房源id
     * @param int $status   状态  1=失效 0=恢复正常(暂时不要)
     * @return json
     */
    public function setForbidHouse()
    {
        if (!in_array($this->getOper('forbidHouse'), $this->_allAuth)) {
            $this->apiReturn(400,[],'无权操作');
        }
        $houseId  = I('post.id', 0, 'intval'); //要删除的房源id
        $status   = I('post.status', 1, 'intval');    //失效处理 1=失效
        if (!is_numeric($houseId) || $houseId<=0 || !in_array($status, [1])) {
            $this->apiReturn(400,[],'参数错误');
        }
        //先获取这条房源信息
        $houseInfo = $this->getBuildingModel()->getHouseInfo('h.mid, h.status, h.trust_status, h.is_delete', ['h.id' => $houseId]);
        if (!$houseInfo) {
            $this->apiReturn(202, [], '不存在该房源');
        }
        if ($houseInfo[0]['mid'] != $this->_pmid) {
            $this->apiReturn(203, [], '没有权限!');
        }
        if ($houseInfo[0]['status'] == 1 || $houseInfo[0]['trust_status'] == 1) {
            $this->apiReturn(204, [], '房源已出租或托管，不能失效处理');
        }
        if ($houseInfo[0]['is_delete'] == $status) {
            $this->apiReturn(205, [], '状态不需要再次更新');
        }

        //失效处理
        $res = $this->getBuildingModel()->updateHouse(['is_delete' => $status], ['id' => $houseId]);
        if ($res) {
            $this->apiReturn(200, [], '失效处理成功');
        } else {
            zft_log('build/update_house_fail', $this->getBuildingModel()->getLastSql());
            $this->apiReturn(400, [], '失效处理失败');
        }
    }

    /**
     * 获取楼宇信息
     * @date   2016-12-30
     * @author Lanlc
     *
     * @param  int  $buildingId  楼宇编号
     *
     * @return json
     */
    public function getBuildingInfo()
    {
        $buildingId = I('post.buildingId', 0, 'intval');
        if (!$buildingId) {
            $this->apiReturn(201, [], '缺少参数');
        }
        $field = 'id';
        $res = $this->getBuildingModel()->getBuildingInfo($buildingId, $field);
        if ($res) {
            $this->apiReturn(200, ['list' => $res['id']], '');
        } else {
            $this->apiReturn(400, [], '没有相关数据');
        }
    }

    /**
     * 托管或运营方获取发布的楼宇信息
     * @date   2016-1-9
     * @author Lanlc
     *
     * @return json
     */
    public function getAllBuilding()
    {
        $res = $this->getBuildingModel()->getOwnerBuildings($this->_pmid);
        if ($res) {
            $this->apiReturn(200, ['list' => $res], '');
        } else {
            $this->apiReturn(201, [], '没有相关数据');
        }
    }

    /**
     * 房源管理 - 获取楼宇房源数据
     * @date   2017-1-3
     * @author Lanlc
     *
     * @return json
     */
    public function index()
    {
        $buildId    = I('post.id', 0, 'intval');           //楼宇id
        $province   = I('post.province', '', 'intval');     //省
        $city       = I('post.city', '', 'intval');         //市
        $country    = I('post.country', '', 'strval');      //区
        $building   = I('post.name', '', 'strval');         //名称
        $address    = I('post.address', '', 'strval');      //地址
        $tradeArea  = I('post.trade_area', 0, 'intval');    //商圈属性
        $status     = I('post.status', 0, 'intval');        //房屋状态，0=全部 1已出租，2未出租
        $room       = I('post.room', '', 'strval');         //房号
        $isDelete   = I('post.is_delete', -1, 'intval');    //房源是否失效 1=是 0=否 -1全部
        $page       = I('post.page', 1, 'intval');
        $pageSize   = I('post.page_size', 20, 'intval');

        $trustHouse = [];
        if (in_array($this->_pdtype, [3, 4])) {
            //托管，运营方先查托管房源
            $trust = $this->getBuildingModel()->getTrustHouseId($this->_pmid);
            if ($trust) {
                $trustHouse = array_column($trust, 'id');
            }
        }

        $auth = [];
        if ($this->_dtype == 7) { //员工限制房源
            $auth = $this->houseAuth($this->_memberId);
        }

        $data =  $this->getBuildingModel()->getBuildingHouse($this->_pmid, $this->_pdtype, $this->_dtype, $buildId, $province, $city, $country, $building,
            $address, $tradeArea, $status, $room, $isDelete, $trustHouse, $auth, $page, $pageSize);

        if ($data) {
            $this->apiReturn(200, $data, '');
        } else {
            $this->apiReturn(400, ['dtype' => $this->_pdtype], '没有相关数据');
        }
    }

    /**
     * 房源管理 - 获取楼宇数据
     * @date   2017-1-3
     * @author Lanlc
     *
     *
     * @return json
     */
    public function getBuilding()
    {
        $province   = I('post.province', '', 'intval');     //省
        $city       = I('post.city', '', 'intval');         //市
        $country    = I('post.country', '', 'strval');      //区
        $building   = I('post.name', '', 'strval');         //名称
        $tradeArea  = I('post.trade_area', 0, 'intval');    //商圈属性
        $isDelete   = I('post.is_delete', -1, 'intval');    //房源是否失效 1=是 0=否 -1全部
        $page       = I('post.page', 1, 'intval');
        $pageSize   = I('post.page_size', 20, 'intval');

        $offSet = ($page-1)*$pageSize;
        $list =  $this->getBuildingModel()->getBuilding($this->_pmid, $this->_pdtype, $province, $city, $country, $building, $tradeArea,$isDelete, $offSet, $pageSize);

        if ($list) {
            $buildIdArr = array_column($list['list'], 'building_id');
            //获取自己的房源数据
            $ownerList = $this->getBuildingModel()->getHouseList(['mid' => $this->_pmid, 'building_id' => ['in', $buildIdArr] ,'is_delete' => 0],
                'id, building_id, area, price, price_type, status');

            foreach ($list['list'] as $k => $v) {//先初始化数据
                $list['list'][$k]['ave_price']   = 0;
                $list['list'][$k]['rent_area']   = 0;
                $list['list'][$k]['rent_money']  = 0;
                $list['list'][$k]['unrent_area'] = 0;
                $list['list'][$k]['count']       = 0;
                $list['list'][$k]['rent_count']  = 0;
                $list['list'][$k]['total_area']  = 0;
                $list['list'][$k]['rent_rate']   = 0;
            }

            if ($ownerList) {//有房源数据
                $ownerHouseBuildId = array_column($ownerList, 'building_id');
                foreach ($list['list'] as $k => $v) {
                    if (in_array($v['building_id'], $ownerHouseBuildId)) {//发布的楼宇存在自己的房源
                        foreach ($ownerList as $key => $owner) {
                            if ($v['building_id'] == $owner['building_id']) {
                                $list['list'][$k]['count'] ++;
                                $list['list'][$k]['total_area'] += $owner['area'];
                                if ($owner['status'] == 1) {//已出租
                                    $list['list'][$k]['rent_count'] ++;
                                    $list['list'][$k]['rent_area'] += $owner['area'];
                                    if ($owner['price_type'] == 1) {
                                        //按平米租
                                        $list['list'][$k]['rent_money'] += $owner['area'] * $owner['price'];
                                    } else {
                                        $list['list'][$k]['rent_money'] +=  $owner['price'];
                                    }
                                } else {
                                    //未出租
                                    $list['list'][$k]['unrent_area'] += $owner['area'];
                                }
                            }  else {
                                continue;
                            }
                        }
                    } else {
                        continue;
                    }
                }
            }
            
            //数据整理
            foreach ($list['list'] as $a => $value) {
                $list['list'][$a]['rent_money']  = yuan($value['rent_money']);//转化为元
                $list['list'][$a]['ave_price']   = $value['rent_area'] == 0 ? round(0, 2) : round(yuan($value['rent_money'] / $value['rent_area']), 2);//平均租价
                $list['list'][$a]['rent_rate']   = $value['total_area'] == 0 ? round(0, 2) : round(($value['rent_area'] / $value['total_area']) * 100, 2);//出租率
            }
            $this->apiReturn(200, $list, '');
        } else {
            $this->apiReturn(400, ['dtype' => $this->_pdtype], '暂无数据');
        }
    }

    /**
     * 房源管理 - 获取房源信息的出租面积，未出租面积，出租率，租售均单价
     * @date   2017-3-8
     * @author wuhao
     *
     * @return json
     */
    public function getHouseSummary()
    {
        if (!in_array($this->_pdtype, [1,3,4])) {
            $this->apiReturn(400,[],'无权操作');
        }
        $buildId    = I('post.id', 0, 'intval');            //楼宇id
        $province   = I('post.province', '', 'intval');     //省
        $city       = I('post.city', '', 'intval');         //市
        $country    = I('post.country', '', 'strval');      //区
        $building   = I('post.name', '', 'strval');         //名称
        $address    = I('post.address', '', 'strval');      //地址
        $tradeArea  = I('post.trade_area', 0, 'intval');    //商圈属性
        $status     = I('post.status', 0, 'intval');        //房屋状态，0=全部 1已出租，2未出租

        $trustHouse = [];
        if (in_array($this->_pdtype, [3, 4])) {
            //托管，运营方先查托管房源
            $trust = $this->getBuildingModel()->getTrustHouseId($this->_pmid);
            if ($trust) {
                $trustHouse = array_column($trust, 'id');
            }
        }

        $houseList = $this->getBuildingModel()->getHouseSummary($this->_pmid, $this->_pdtype, $buildId, $province, $city, $country,$building,
            $address, $tradeArea, $status, $trustHouse);

        if (!$houseList) {
            $this->apiReturn(400, [], '暂无数据');
        }
        $rentArea = $unRentArea = $rentMoney = 0;//出租面积 ， 未出租面积， 出租总收入
        foreach ($houseList as $key => $house) {
            if ($house['status'] == 1) {
                //出租中
                $rentArea  += $house['area'];
                if ($house['price_type'] == 1) {//按平米租
                    $rentMoney += $house['area'] * $house['price'];
                } else {//按月租
                    $rentMoney += $house['price'];
                }

            } else {
                $unRentArea += $house['area'];
            }
        }
        $rentMoney = yuan($rentMoney);
        $rentRate  = round(($rentArea / ($rentArea + $unRentArea)) * 100 , 2);
        if ($rentArea != 0) {
            $avePrice  = round($rentMoney / $rentArea, 2);
        } else {
            $avePrice = 0;
        }
        $data = [
            'rent_area'   => $rentArea,
            'unrent_area' => $unRentArea,
            'rent_rate'   => $rentRate,
            'ave_price'   => $avePrice,
        ];
        $this->apiReturn(200, $data, '');
    }

    /**
     * 楼宇管理 - 获取托管楼宇的统计信息(托管楼宇总数、自有楼宇、托管楼宇总面积、已出租面积、未出租面积、已出租面积占比、空置面积占比和入驻企业数)
     * @date   2017-3-17
     * @author wuhao
     *
     * @return json
     */
    public function getBuildingStatics()
    {
        if (!in_array($this->_pdtype, [1,3,4])) {
            $this->apiReturn(400,[],'无权操作');
        }
        $trustModel = new Trust();
        $countTrust = $countSelf = $rentArea = $unrentArea = $rentRate = $unrentRate = $trustTotalArea = 0;

        //查自己发布的楼宇
        $buildList = $this->getBuildingModel()->getBuildingList(['mid' => $this->_pmid, 'is_delete' => 0],
            'id');
        if ($buildList) {
            $selfBuilding = array_unique(array_column($buildList, 'id'));
            $countSelf    = count($selfBuilding);//楼宇总数
        }
        //查自己的房源
        $houseList = $this->getBuildingModel()->getHouseList(['mid' => $this->_pmid, 'is_delete' => 0], 'id, house_number, area, status');
        if ($houseList) {
            //$selfHouseNumber = array_column($houseList, 'house_number');
            foreach ($houseList as $h) {
                //出租情况 1=已出租
                $h['status'] == 1 ? $rentArea += $h['area'] : $unrentArea += $h['area'];
            }
        }

        //查托管房源信息
        $hids  = $houseNumbers = [];
        $where = ['trust_id' => $this->_pmid, 'begintime' => ['elt', time()], 'endtime' => ['egt', time()], 'status' => 1];
        $field = 'owner_id, building_id';//业主id, 楼宇id
        $trustInfo = $trustModel->getTrustedInfo($where, $field);
        if ($trustInfo) {
            //对应的房源id信息
            foreach ($trustInfo as $a => $b) {
                $hid = $this->getBuildingModel()->getHouseInfoByUser($b['owner_id'], $b['building_id'], 'id, house_number');
                if ($hid) {
                    foreach ($hid as $k => $v) {
                        $hids[]         = $v['id'];
                        $houseNumbers[] = $v['house_number'];
                    }
                }
            }

            //获取托管房源的信息
            $trustHouse = $this->getBuildingModel()->getHouseList(['id' => ['in', $hids], 'is_delete' => 0],
                'id, house_number, area, status');

            if ($trustHouse) {//计算托管的出租面积情况
                foreach ($trustHouse as $t) {
                    $t['status'] == 1 ? $rentArea += $t['area'] : $unrentArea += $t['area'];
                    $trustTotalArea += $t['area'];
                }
            }
            //获取托管房源的租赁合同的入驻企业数
            /* $business = $leaseModel->getContractInfo(['house_number' => ['in', $houseNumbers], 'status' => 1, 'ordermode' => 1]);
             $businessNum = count($business);*/

            //托管楼宇总数 = 托管的楼宇id和自己的楼宇id的差集
            $trustBuilding = array_unique(array_column($trustInfo, 'building_id'));
            $diff          = array_diff($trustBuilding, $selfBuilding);
            $countTrust    = count($diff);
        }

        $count      = $countSelf + $countTrust;//楼宇总数
        $totalArea  = $rentArea + $unrentArea;//总面积
        if ($totalArea) {
            $rentRate   = round(($rentArea / $totalArea) * 100, 2);//出租率
            $unrentRate = round(($unrentArea / $totalArea) * 100, 2);//空置率
        }

        $data       = [
            'count'            => $count,
            'count_self'       => $countSelf,
            'count_trust'      => $countTrust,
            'rent_area'        => $rentArea,
            'unrent_area'      => $unrentArea,
            'rent_rate'        => $rentRate,
            'unrent_rate'      => $unrentRate,
            'trust_total_area' => $trustTotalArea,
        ];
        $this->apiReturn(200, $data, '');
    }

    /**
     * 托管结算 - 搜索房源数据
     * @date   2017-1-20
     * @author wuhao
     *
     * @param  int  $province 省份
     * @param  int  $city     城市
     * @param  int  $country  区域
     * @param  int  $name     楼宇名称
     * @param  int  $page     页数
     * @param  int  $pageSize 每页个数
     * @return json
     */
    public function getTrustBuilding()
    {
        $province = I('post.province', '', 'intval');     //省
        $city     = I('post.city', '', 'intval');         //市
        $country  = I('post.country', '', 'strval');      //区
        $building = I('post.name', '', 'strval');         //名称
        $page     = I('post.page', 1, 'intval');
        $pageSize = I('post.page_size', 3, 'intval');

        $auth = [];
        if ($this->_dtype == 7) { //员工限制房源
            $auth = $this->houseAuth($this->_memberId);
        }
        $data     = $this->getBuildingModel()->getTrustBuilding($this->_pmid, $this->_dtype, $province, $city, $country, $building, $auth,  $page, $pageSize);
        if (!$data) {
            $this->apiReturn(201, [], '没有数据');
        } else {
            $this->apiReturn(200, $data, '');
        }
    }

    /**
     * 托管结算 -- 根据楼宇ID获取对应的房源信息
     * @date   2017-1-20
     * @author wuhao
     *
     * @param  int  $id       楼宇ID
     * @param  int  $page     页数
     * @param  int  $pageSize 每页个数
     *
     * @return json
     */
    public function getHouseByBuildingId()
    {
        $id       = I('post.id', '', 'intval');
        $page     = I('post.page', 1, 'intval');
        $pageSize = I('post.page_size', 3, 'intval');
        //$id=46;
        if (!$id || !is_numeric($page) || !is_numeric($pageSize)) {
            $this->apiReturn(400, [], '参数错误!');
        }

        $data = $this->getBuildingModel()->getHouseByBuildingId($id, $this->_pdtype, $this->_pmid, $page, $pageSize);
        if ($data) {
            $mid  = array_unique(array_column($data['list'], 'mid'));
            if (count($mid) >1) {
                $this->apiReturn(202, [], '一份合同只能有一个业主');
            }

            //获取业主信息
            $memberModel = new Member();
            $midInfo = $memberModel->getMemberInfo(['id' => $mid[0]], 'nickname, mobile');
            foreach ($data['list'] as $k => $v) {
                $data['list'][$k]['nickname'] = $midInfo[0]['nickname'];
                $data['list'][$k]['mobile']   = $midInfo[0]['mobile'];
            }
            $this->apiReturn(200, $data, '');
        } else {
            $this->apiReturn(201, [], '没有数据');
        }

    }

    /**
     * 获取签约房源信息
     * @date   2016-1-23
     * @author banjin
     *
     * @return json
     */
    public function getLeaseHouse()
    {
        $province   = I('post.province', '', 'intval');//省
        $city       = I('post.city', '', 'intval');    //市
        $country    = I('post.country', '', 'strval'); //区
        $bName      = I('post.bName', '', 'strval');   //楼宇名称
        $bAddress   = I('post.bAddress', '', 'strval');//地址
        $status     = I('post.status', 0, 'intval');   //出租状态
        $areaBegin  = I('post.areaBegin', 0, 'intval');//面积
        $areaEnd    = I('post.areaEnd', 0, 'intval');
        $page       = I('post.page', 1, 'intval');
        $pageSize   = I('post.page_size', 10, 'intval');

        $trustHouse = [];
        //托管，运营方先查托管房源
        $trust = $this->getBuildingModel()->getTrustHouseId($this->_pmid);
        if ($trust) {
            $trustHouse = array_column($trust, 'id');
        }

        $leaseModel = new Lease();
        // var_dump($bName);exit;
        $field = 'h.id house_id, h.house_number, h.room, h.area, h.price, h.price_type, h.mid, b.province, b.city, b.country,
         b.name, b.address, b.building_count, b.id building_id, b.property_id, b.hydropower_id, b.trade_area';
        $where = [];
        if ($province) {
            $where['b.province'] = $province;
        }
        if ($city) {
            $where['b.city'] = $city;
        }
        if ($country) {
            $where['b.country'] = $country;
        }
        if ($areaBegin && $areaEnd) {
            $where['h.area'] = ['between',[$areaBegin, $areaEnd]];
        }
        if ($status === 0) {
            $where['h.status'] = 2;//未出租
        } else {
            $where['h.status'] = 1;//已出租
        }
        $where['h.is_delete'] = 0;
        if ($bName) {
            $where['b.name'] = ['LIKE', '%'.$bName.'%'];
        }
        if ($bAddress) {
            $where['b.address'] = ['LIKE', '%'.$bAddress.'%'];
        }

        $res = $leaseModel->getLeaseHouse($field, $where, $this->_pmid, $trustHouse, $page, $pageSize);

        if ($res) {
            foreach ($res['list'] as $k => $v) {
                $res['list'][$k]['price'] = yuan($v['price']);
            }
            $this->apiReturn(200, $res, '查询成功');
        } else {
            $this->apiReturn(201, [], '没有相关数据');
        }
    }

    /**
     * 收入管理 - 获取楼宇的统计信息
     * @date   2017-3-23
     * @author wuhao
     *
     * @return json
     */
    public function incomeBuildSummary()
    {
        if (in_array($this->_pdtype, [5, 6])) {//物业水电获取相关的楼宇
            $ownerList = [];
            $owner     = $this->getBuildingModel()->getBuildingList(['property_id|hydropower_id' => $this->_pmid, 'is_delete' => 0], 'id');
            //获取总数,已出租,未出租数量
            $buildCount = $totalCount = $rentCount = $unrentCount = 0;
            if ($owner) {
                $ownerList = array_column($owner, 'id');
                $houseList = $this->getBuildingModel()->getHouseInfoByBuildingId($ownerList, 'id, building_id,  status');
                //获取楼宇总数
                $buildCount = count(array_unique(array_column($houseList, 'building_id')));
                $totalCount = count($houseList);
                foreach ($houseList as $key => $house) {
                    ($house['status'] == 1) ? $rentCount++ : $unrentCount++;
                }
            }

            $data = [
                'build_count'  => $buildCount,
                'total_count'  => $totalCount,
                'rent_count'   => $rentCount,
                'unrent_count' => $unrentCount,
                'dtype'        => $this->_pdtype,
            ];
            $this->apiReturn(200, $data, '');
        } elseif (in_array($this->_pdtype, [1,3,4])) {//业主，运营方和托管

            $trustHouse = [];
            //托管，运营方先查托管房源
            $trust = $this->getBuildingModel()->getTrustHouseId($this->_pmid);
            if ($trust) {
                $trustHouse = array_column($trust, 'id');
            }

            //获取自己的房源 (业主,托管,运营方)
            $ownerList = [];
            $owner     = $this->getBuildingModel()->getHouseList(['mid' => $this->_pmid, 'is_delete' => 0], 'id');
            if ($owner) {
                $ownerList = array_column($owner, 'id');
            }

            //所有的房源
            $allList = empty($ownerList) ? $trustHouse : array_merge($trustHouse, $ownerList);
            //获取总数,已出租,未出租数量
            $buildCount = $totalCount = $rentCount = $unrentCount = 0;
            if ($allList) {
                //获取对应的信息
                $houseList = $this->getBuildingModel()->getHouseList(['id' => ['in', $allList], 'is_delete' => 0], 'id, building_id,  status');

                //获取楼宇总数
                $buildCount = count(array_unique(array_column($houseList, 'building_id')));
                $totalCount = count($houseList);
                foreach ($houseList as $key => $house) {
                    ($house['status'] == 1) ? $rentCount++ : $unrentCount++;
                }
            }

            $data = [
                'build_count'  => $buildCount,
                'total_count'  => $totalCount,
                'rent_count'   => $rentCount,
                'unrent_count' => $unrentCount,
                'dtype'        => $this->_pdtype,
            ];
            $this->apiReturn(200, $data, '');
        } else {
            $this->apiReturn(200, [], '');
        }
    }

    /**
     * 获取物业，水电公司，运营方或托管对应的楼宇列表
     * @date   2017-06-02
     * @author wuhao
     *
     * @return json
     */
    public function getOwnerBuilding()
    {
        if ($this->_pdtype == 5) {//物业
            $where = ['property_id' => $this->_pmid, 'is_delete' => 0];
        } elseif ($this->_pdtype == 6) {//水电
            $where = ['hydropower_id' => $this->_pmid, 'is_delete' => 0];
        } elseif ($this->_pdtype == 3 || $this->_pdtype == 4) {//运营方或托管
            $where = ['mid' => $this->_pmid, 'is_delete' => 0];
        } elseif ($this->_pdtype == 0) { //管理员
            $where = [];
        } else {
            $this->apiReturn(400, [], '没有当前用户管理的楼宇');
        }
        $buildModel = new Building();
        $res = $buildModel->getBuildingList($where, 'id, name');
        if (!$res) {
            $this->apiReturn(400, [], '没有当前用户管理的楼宇');
        } else {
            $this->apiReturn(200, $res, '');
        }
    }
}
